package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuElasticSearchModleTO;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.SkuHasStockVo;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.SeckillFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService imagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService attrValueService;

    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * //TODO 高级部分完善
     *
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

        //1: 保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        //2: 保存spu 的描述图片 pms_spu_info_desc
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",", vo.getDecript()));
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        //3: 保存 spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        imagesService.saveImages(spuInfoEntity.getId(), images);

        //4: 保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrValues());
            if (attrEntity != null) {
                valueEntity.setAttrName(attrEntity.getAttrName());
            }
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setSpuId(spuInfoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);
        //TODO 4-5:保存spu的积分信息 gulimall_sms=>sms_spu_bounds
        SpuBoundTo boundTo = new SpuBoundTo();
        Bounds bounds = vo.getBounds();
        BeanUtils.copyProperties(bounds, boundTo);
        boundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(boundTo);
        if (r.getCode() != 0) {
            log.error("远程调用spu保存积分信息失败==");
        }
        //5: 保存当前spu队形的所有的sku信 息
        //5.1: 保存sku的基本信息 pms_sku_info
        List<Skus> skus = vo.getSkus();
        if (CollectionUtils.isEmpty(skus)) {
            skus.forEach(item -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                String imageDefault = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        imageDefault = image.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(imageDefault);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imagesEntityList = item.getImages().stream().map(img -> {
                    SkuImagesEntity imagesEntity = new SkuImagesEntity();
                    imagesEntity.setSkuId(skuId);
                    imagesEntity.setImgUrl(img.getImgUrl());
                    imagesEntity.setDefaultImg(img.getDefaultImg());
                    return imagesEntity;
                }).filter(entry -> {
                    return !StringUtils.isEmpty(entry.getImgUrl());
                }).collect(Collectors.toList());
                //5.2: 保存sku的图片信息 pms_sku_images
                skuImagesService.saveBatch(imagesEntityList);

                //5.3: 保存sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> valueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity saleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, saleAttrValueEntity);
                    saleAttrValueEntity.setSkuId(skuId);
                    return saleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(valueEntities);
                //5.4: 保存sku的优惠,满减等信息: gulimall_sms=>sms_sku_loader,sms_sku_full_reduction,sms_member_price
                SkuReductionTo reductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(vo, reductionTo);
                reductionTo.setSkuId(skuId);
                if (reductionTo.getFullCount() > 0 || reductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R result = couponFeignService.saveSkuReduction(reductionTo);
                    if (result.getCode() != 0) {
                        log.error("远程sku保存优惠信息调用失败==");
                    }
                }
            });
        }

    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        this.baseMapper.insert(infoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && "0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && "0".equals(catelogId)) {
            wrapper.eq("catelog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架功能
     **/
    @Override
    public void skuUp(Long spuId) {


        // 组装需要的数据
        //1:  查询当前skuId对应的sku所有信息,品牌名字
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySkuId(spuId);

        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //5:查询当前所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> entityList = attrValueService.baseAttrlistforspu(spuId);
        List<Long> attrIds = entityList.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        //根据attrId查询当前所有属性的ID
        List<Long> searchAttrs = attrService.selectSearchAttrs(attrIds);
        Set<Long> set = new HashSet(searchAttrs);
        //过滤不需要检索的属性并封装成modleTO里面的attrs属性
        List<SkuElasticSearchModleTO.Attrs> attrsList = entityList.stream().filter(item -> {
            //set去重
            return set.contains(item.getAttrId());
        }).map(item -> {
            //属性封装
            SkuElasticSearchModleTO.Attrs attrModle = new SkuElasticSearchModleTO.Attrs();
            BeanUtils.copyProperties(item, attrModle);
            return attrModle;
        }).collect(Collectors.toList());

        //7:远程查询该sku是否还有库存
        Map<Long, Boolean> hasStockMap = null;
        try {
            R skuStock = wareFeignService.getSkuStock(skuIds);
            //封装成一个map数据类型,key是skuID,value是boolean类型的hasStock
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            hasStockMap = skuStock.getDate(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("远程查询库存服务出现问题,原因是{}",e);
        }

        Map<Long, Boolean> finalHasStockMap = null;
        List<SkuElasticSearchModleTO> collect = skus.stream().map(sku -> {
            SkuElasticSearchModleTO modleTO = new SkuElasticSearchModleTO();
            BeanUtils.copyProperties(sku,modleTO);
            modleTO.setSkuPrice(sku.getPrice());
            modleTO.setSkuImg(sku.getSkuDefaultImg());
            //设置库存,根据hasStockMap或者数据中的boolean值
            if (finalHasStockMap == null){
                modleTO.setHasStock(true);
            }else {
                modleTO.setHasStock(finalHasStockMap.get(sku.getSkuId()));
            }
            //2: 热度评分,刚上架的商品,后台都定一个默认值,比如0
            modleTO.setHotScore(0L);
            //3: 查询品牌和分类的名字信息
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            modleTO.setBrandName(brandEntity.getName());
            modleTO.setBrandImg(brandEntity.getLogo());

            //4:分类ID
            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            modleTO.setCatalogName(categoryEntity.getName());

            //设置检索属性
            modleTO.setAttrs(attrsList);

            return modleTO;
        }).collect(Collectors.toList());
        //6: 发送数据给ES保存
        R r = searchFeignService.productStatusUp(collect);
        if (r.getCode() == 0){
            //成功,修改当前spu的上架状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            //远程调用失败
            //TODO 重复调用的问题,接口的幂等性,远程接口失败后的重试机制
            /**
             * 失败了,feign会进行重试
             * feign的调用过程:
             * 1: 构造请求参数,将请求对象转为json数据
             *    RequestTemplate template = buildTemplateFromArgs.create(args)
             * 2: 发送请求进行执行(执行成功会解码响应数据)executeAndDecode(template)
             * 3: 执行请求会有重试机制
             *   whlie(true){
             *       retryer.continueOrPropagate(e)}
             **/
        }
    }

    @Override
    public SpuInfoEntity getInfoBySkuId(Long skuId) {
        SkuInfoEntity entity = skuInfoService.getById(skuId);
        SpuInfoEntity spuInfoEntity = getById(entity.getSpuId());
        return spuInfoEntity;
    }


}